// request.js
class Request {
    constructor() {
        // 根据环境设置基础 URL
        this.baseUrl = process.env.NODE_ENV === "development"
            ? 'http://121.43.210.84/'
            : 'http://121.43.210.84/';

        console.log(
            process.env.NODE_ENV === "development"
                ? "======================开发环境======================"
                : "======================正式环境======================"
        );
    }

    // 设置请求方法
    request(options = {}, isDownLoad = false) {
        options.header = options.header || {};
        options.header['Authorization'] = uni.getStorageSync('token');
		let obj = {
			url: this.baseUrl + (options.url || ''),
			sslVerify: false,
			method: options.method || 'GET',
			data: options.data || {},
			header: options.header
		}
		
		if (isDownLoad) {
			obj.responseType = "blob"
		}
        // options.header['tenant'] = this.baseUrl.split(".")[0].split("//")[1];
        return new Promise((resolve, reject) => {
            uni.request(obj).then(data => {
                if (data.data.code === 1002) {
                    uni.clearStorageSync();
                    // store.commit("clearUserInfo", {})
                }
                resolve(data.data);
            }).catch(error => {
                reject(error);
            });
        });
    }

    // GET 方法封装
    get(url, data, options = {}) {
        options.method = 'GET';
        options.data = data;
        options.url = url;
        return this.request(options);
    }

    // POST 方法封装
    post(url, data, options = {}, isDownLoad= false) {
        options.method = 'POST';
        options.data = data;
        options.url = url;
        return this.request(options , isDownLoad);
    }

    // 返回 baseUrl
    getUrl() {
        return this.baseUrl;
    }
}

// 实体化
const requestInstance = new Request();

// 将 `http` 绑定到 globalThis
globalThis.$request = requestInstance;